package reports.builders;

import java.util.Iterator;

public class HTMLBuilder implements IBuilder<String>
{
  private StringBuilder html = new StringBuilder();

  public HTMLBuilder()
  {
    html.append("<html>");
    html.append("<head><style>" + "html, body { font-family: sans-serif; }"
        + "table { width: 100%; border: 1px solid #46f; -webkit-border-radius: 6px; }"
        + "th { background: #46f; text-align: center; }"
        + "td { padding: 1px 5px 2px 5px; border-width: 1px; border-style: solid; "
        + "border-color: #46f; background: #8af; text-align: right; }"
        + "td:first-child { text-align:left; }"
        + "th:first-child { -webkit-border-radius: 4px 0px 0px 0px; }"
        + "th:last-child { -webkit-border-radius: 0px 4px 0px 0px; }"
        + "tr:last-child td:first-child { -webkit-border-radius: 0px 0px 0px 4px; }"
        + "tr:last-child td:last-child { -webkit-border-radius: 0px 0px 4px 0px; }"
        + "</style></head>");
    html.append("<body>");
  }

  @Override
  public HTMLBuilder addTitle(String title)
  {
    title = title.replace("\n", "<br/>");
    html.append("<h1>" + title + "</h1>");
    return this;
  }

  @Override
  public HTMLBuilder addSubTitle(String subTitle)
  {
    subTitle = subTitle.replace("\n", "<br/>");
    html.append("<h2>" + subTitle + "</h2>");
    return this;
  }

  @Override
  public HTMLBuilder startTable(int columns)
  {
    html.append("<table cellspacing=0>");
    return this;
  }

  @Override
  public HTMLBuilder addTableHeader(Iterator<String> headers)
  {
    html.append("<thead>");
    html.append("<tr>");

    while (headers.hasNext())
    {
      String header = headers.next();
      header = header.replace("\n", "<br/>");
      html.append("<th>" + header + "</th>");
    }

    html.append("</tr>");
    html.append("</thead>");
    return this;
  }

  @Override
  public HTMLBuilder addRow(Iterator<String> row)
  {
    html.append("<tr>");

    while (row.hasNext())
    {
      String cell = row.next();
      cell = cell.replace("\n", "<br/>");
      html.append("<td>" + cell + "</td>");
    }

    html.append("</tr>");
    return this;
  }

  @Override
  public HTMLBuilder endTable()
  {
    html.append("</table>");
    return this;
  }

  @Override
  public HTMLBuilder insertPadding(int value)
  {
    return this;
  }

  @Override
  public HTMLBuilder addParagraph(String text)
  {
    text = text.replace("\n", "<br/>");
    html.append("<p>" + text + "</p>");
    return this;
  }

  @Override
  public HTMLBuilder addList(Iterator<String> list)
  {
    html.append("<ul>");

    while (list.hasNext())
    {
      String item = list.next();
      item = item.replace("\n", "<br/>");
      html.append("<li>" + item + "</li>");
    }

    html.append("</ul>");
    return this;
  }

  @Override
  public String getData()
  {
    return html.toString() + "</body></html>";
  }
}
